import bomService, { type PageListReq } from "@/api/services/base/bomService";
import CustomTable from "@/components/grid/CustomTable";
import TableDictTag from "@/components/grid/TableDictTag";
import useDictionary from "@/hooks/system/useDictionary";
import { t } from "@/locales/i18n";
import SingleMaterialSelector from "@/pages/components/selector/SingleMaterialSelect";
import { ExportOutlined } from "@ant-design/icons";
import { Button, Card, Col, Drawer, Form, Input, Row, Select, Space, Spin, Switch, Tabs } from "antd";
import type { ColumnsType } from "antd/es/table";
import { useEffect, useRef, useState } from "react";
import { toast } from "sonner";
import type { Bom } from "./entity";
import BomItemPage, { type BomItemHandles } from "./item";

export default function BomPage() {
	const itemRef = useRef<BomItemHandles>(null);

	const [loading, setLoading] = useState(false);
	const [submitLoading, setSubmitLoading] = useState(false);
	const [queryParams, setQueryParams] = useState<PageListReq>({
		materialId: undefined,
		status: undefined,
		page: 1,
		pageSize: 10,
	});
	const [total, setTotal] = useState(0);
	const [list, setList] = useState<Bom[]>([]);
	const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
	const [drawerVisible, setDrawerVisible] = useState(false);
	const [editingData, setEditingData] = useState<Bom | null>(null);
	const [form] = Form.useForm();
	const [isView, setIsView] = useState(true);

	const [selectVisiable, setSelectVisiable] = useState(false);

	//动态设置表格高度
	const [tableScrollY, setTableScrollY] = useState(0);
	const PAGE_OFFSET_HEIGHT = 405;
	const updateTableHeight = () => {
		const newHeight = window.innerHeight - PAGE_OFFSET_HEIGHT;
		setTableScrollY(newHeight > 200 ? newHeight : 200); // 保证最小高度
	};

	useEffect(() => {
		updateTableHeight(); // 初始化
		window.addEventListener("resize", updateTableHeight);
		return () => window.removeEventListener("resize", updateTableHeight);
	}, []);

	const statusOptions = useDictionary("system_status");

	const columns: ColumnsType<Bom> = [
		{
			title: "物料编码",
			width: 120,
			key: "materialCode",
			dataIndex: "materialCode",
		},
		{
			title: "物料名称",
			width: 120,
			key: "materialName",
			dataIndex: "materialName",
		},
		{
			title: "是否启用",
			width: 120,
			key: "status",
			dataIndex: "status",
			render: (_, record) => <TableDictTag dictCode="system_status" value={record.status ?? ""} />,
		},
		{
			title: "版本号",
			width: 120,
			key: "version",
			dataIndex: "version",
		},
		{
			title: "是否默认版本",
			width: 120,
			key: "isDefault",
			dataIndex: "isDefault",
			render: (_, record) => (
				<Switch value={record.isDefault === "1"} onChange={(checked: boolean) => updateDefault(record, checked)} />
			),
		},
		{
			title: "生效日期",
			width: 120,
			key: "effectiveDate",
			dataIndex: "effectiveDate",
		},
		{
			title: "备注",
			width: 120,
			key: "remark",
			dataIndex: "remark",
		},
		{
			title: "操作",
			fixed: "right",
			key: "operation",
			align: "center",
			width: 100,
			render: (_, record) => (
				<Space>
					<Button type="link" onClick={() => handleView(record)}>
						{t("common.view")}
					</Button>
					<Button type="link" onClick={() => handleEdit(record)}>
						{t("common.edit")}
					</Button>
					{record.status === "1" ? (
						<Button type="link" onClick={() => updateStatus(record, "0")}>
							停用
						</Button>
					) : record.status === "0" ? (
						<Button type="link" onClick={() => updateStatus(record, "1")}>
							启用
						</Button>
					) : null}
				</Space>
			),
		},
	];

	//加载表格数据
	const fetchPageList = () => {
		setLoading(true);
		bomService
			.pageList(queryParams)
			.then((res) => {
				setList(res.records);
				setTotal(res.total);
			})
			.catch((error) => {
				console.log(error);
				toast.error("获取数据失败！", error);
			})
			.finally(() => {
				setLoading(false);
			});
	};

	// biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
	useEffect(() => {
		fetchPageList();
	}, [queryParams]);

	//更新状态
	const updateStatus = (record: Bom, status: string) => {
		if (status === "1" && record.isDefault === "1") {
			toast.warning("启用该版本为默认版本。");
		}

		const params: Bom = {
			...record,
			status: status,
		};
		bomService
			.updateStatus(params)
			.then((res) => {
				toast.success("修改成功！");
				fetchPageList();
			})
			.catch((error) => {
				toast.error("修改失败！");
				console.error(error);
			});
	};

	const updateDefault = (record: Bom, checked: boolean) => {
		const params: Bom = {
			...record,
			isDefault: checked ? "1" : "0",
		};

		bomService
			.updateDefault(params)
			.then((res) => {
				toast.success("修改成功！");
				fetchPageList();
			})
			.catch((error) => {
				toast.error("修改失败！");
				console.error(error);
			});
	};

	//选择其他页
	const handlePageChange = (newPage: number, newPageSize: number) => {
		setQueryParams((prev) => ({
			...prev,
			page: newPage,
			pageSize: newPageSize,
		}));
	};

	//触发编辑按钮
	const handleEdit = (bom: Bom) => {
		setEditingData(bom);
		form.setFieldsValue(bom);
		setDrawerVisible(true);
		setIsView(false);
	};

	//触发视图按钮
	const handleView = (bom: Bom) => {
		setEditingData(bom);
		form.setFieldsValue(bom);
		setIsView(true);
		setDrawerVisible(true);
	};

	//提交表单数据
	const handleSubmit = async (values: Bom) => {
		try {
			setSubmitLoading(true);

			//产品BOM
			const deleteItemIds = itemRef.current?.getDeleteIds();
			const addItems = itemRef.current?.getAddList();
			const updateItems = itemRef.current?.getUpdateList();

			const data = {
				...values,
				id: editingData?.id,
				deleteItemIds: deleteItemIds,
				addItems: addItems,
				updateItems: updateItems,
			};
			if (editingData) {
				await bomService.update(data);
				toast.success("更新产品BOM成功");
			} else {
				await bomService.add(data);
				toast.success("创建产品BOM成功");
			}
			setDrawerVisible(false);
			setEditingData(null);
			form.resetFields();
			fetchPageList();
		} catch (error) {
			toast.error(`保存失败: ${error.message}`);
		} finally {
			setSubmitLoading(false);
		}
	};

	const handleDrawerClose = () => {
		setDrawerVisible(false);
		setEditingData(null);
		form.resetFields();
	};

	const handleAdd = () => {
		setEditingData(null);
		form.resetFields();
		setDrawerVisible(true);
		setIsView(false);
	};

	const handleDelete = async () => {
		try {
			setLoading(true);
			await bomService.remove(selectedRowKeys);
			toast.success("删除产品BOM成功");
			setSelectedRowKeys([]);
			fetchPageList();
		} catch (error) {
			toast.error(`删除失败: ${error.message}`);
		} finally {
			setLoading(false);
		}
	};

	const openSelectMaterial = (id: React.Key) => {
		setSelectVisiable(true);
	};

	const handleSelectMaterial = (material: any) => {
		setSelectVisiable(false);
		if (material) {
			const { id, materialCode, materialName, spec } = material;
			form.setFieldsValue({
				materialId: id,
				materialCode: materialCode,
				materialName: materialName,
				materialSpec: spec,
			});
		}
	};

	return (
		<Spin spinning={submitLoading} tip="数据提交中..." size="large">
			<Card className="mb-4">
				<Form
					layout="inline"
					onFinish={(values) => {
						setQueryParams((prev) => ({
							...prev,
							...values,
							page: 1,
						}));
					}}
				>
					<Form.Item name="materialId" label="物料产品ID">
						<Input placeholder="请输入物料产品ID" allowClear />
					</Form.Item>
					<Form.Item name="status" label="是否启用">
						<Select options={statusOptions} allowClear style={{ width: 170 }} />
					</Form.Item>
					<Form.Item>
						<Button type="primary" htmlType="submit">
							查询
						</Button>
						<Button
							className="ml-2"
							onClick={() => {
								setQueryParams({ page: 1, pageSize: 10 });
							}}
						>
							重置
						</Button>
					</Form.Item>
				</Form>
			</Card>
			<div className="h-4" />
			<Card>
				<CustomTable
					loading={loading}
					columnsConfig={columns}
					dataSource={list}
					total={total}
					selectedRowKeys={selectedRowKeys}
					setSelectedRowKeys={setSelectedRowKeys}
					current={queryParams.page}
					pageSize={queryParams.pageSize}
					onRefresh={fetchPageList}
					onPageChange={handlePageChange}
					selectable
					toolbarButtons={
						<>
							<Button type="primary" onClick={handleAdd}>
								新增
							</Button>
							<Button danger disabled={selectedRowKeys.length === 0} onClick={handleDelete}>
								删除
							</Button>
						</>
					}
					scroll={{ y: tableScrollY }}
				/>
			</Card>
			<Drawer
				title={editingData ? "编辑产品BOM" : "新增产品BOM"}
				width={800}
				open={drawerVisible}
				onClose={handleDrawerClose}
				footer={
					<div className="flex justify-end gap-2">
						<Button onClick={handleDrawerClose}>取消</Button>
						{!isView && (
							<Button type="primary" loading={submitLoading} onClick={() => form.submit()}>
								确定
							</Button>
						)}
					</div>
				}
			>
				<Form form={form} labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} onFinish={handleSubmit} disabled={isView}>
					<Row gutter={16}>
						<Col span={12}>
							<Form.Item name="materialId" label="物料ID" hidden>
								<Input />
							</Form.Item>
							<Form.Item label="物料编码" name="materialCode" rules={[{ required: true, message: "请选择物料编码" }]}>
								<Input.Search
									placeholder="请选择生产物料"
									allowClear
									enterButton={<ExportOutlined />}
									onSearch={openSelectMaterial}
								/>
							</Form.Item>
						</Col>
						<Col span={12}>
							<Form.Item name="materialName" label="物料名称">
								<Input disabled />
							</Form.Item>
						</Col>
					</Row>

					<Row gutter={16}>
						<Col span={12}>
							<Form.Item
								name="version"
								label="版本号"
								rules={[
									{
										required: true,
										message: "请填写版本号",
									},
								]}
							>
								<Input placeholder="请输入版本号" allowClear />
							</Form.Item>
						</Col>

						<Col span={12}>
							<Form.Item name="isDefault" label="是否默认版本">
								<Switch
									checkedChildren="是"
									unCheckedChildren="否"
									checkedValue="1"
									unCheckedValue="0"
									disabled={isView}
								/>
							</Form.Item>
						</Col>
					</Row>

					<Row gutter={16}>
						<Col span={24}>
							<Form.Item name="remark" label="备注" labelCol={{ span: 3 }} wrapperCol={{ span: 21 }}>
								<Input.TextArea />
							</Form.Item>
						</Col>
					</Row>

					<Tabs
						defaultActiveKey="1"
						items={[
							{
								key: "1  ",
								label: "产品BOM",
								children: <BomItemPage ref={itemRef} parentId={editingData?.id} />,
							},
						]}
					/>
				</Form>
			</Drawer>

			{/* 物料选择器 */}
			<SingleMaterialSelector
				open={selectVisiable}
				onCancel={() => setSelectVisiable(false)}
				onOk={(item) => handleSelectMaterial(item)}
			/>
		</Spin>
	);
}
